package com.dyzx.hbb.common.utils;


import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

public class ValidatorUtil {

    private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();
    private static final Validator VALIDATOR = VALIDATOR_FACTORY.getValidator();
    private static final String ERROR_MESSAGE_PREFIX = "导入数据校验失败：";

    public static <R> void validate(R item) throws RuntimeException {
        if (item == null) {
            throw new IllegalArgumentException("输入项不能为空");
        }

        Set<ConstraintViolation<R>> violations = VALIDATOR.validate(item);
        if (!violations.isEmpty()) {
            StringBuilder errorMessage = new StringBuilder(ERROR_MESSAGE_PREFIX);
            for (ConstraintViolation<R> violation : violations) {
                errorMessage.append(violation.getPropertyPath()).append(": ").append(violation.getMessage()).append("; ");
            }
            logError(errorMessage.toString());
            throw new RuntimeException(errorMessage.toString());
        }
    }

    private static void logError(String message) {
        // 使用日志框架记录错误信息
        // 例如：logger.error(message);
    }
}